"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 系统内部使用工具
Case Name   : 执行gs_ctl failover时添加-W参数，是否显示failover开始而不显示结束
Create At   : 2021/01/20
Owner       : opentestcase015
Description :
    1.关闭主数据库(主机执行)
    2.在备机上执行failover，与-W结合使用，是否只有failover开始提示无
    完成提示（备机执行）
    3.执行refrashconf进行信息写入
    4.重启集群
    5.检查主备是否切换成功
    6.恢复环境
Expect      :
    1.关闭主数据库成功
    2.在备机上执行failover成功,无failover完成的提示信息
    3.执行refrashconf进行信息写入
    4.重启集群成功
    5.检查主备状态，主备切换成功
    6.成功
History     :
    modeified by opentestcase042 at 2022-7-25:优化用例，修改恢复环境步骤
    Modified by opentestcase027 2023/1/12: 优化用例步骤格式及一主两备判断方式
"""

import time
import unittest
import os
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro

LOG = Logger()
primary_sh = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 != primary_sh.get_node_num(), '非1+2环境不执行')
class SystemInternalTools(unittest.TestCase):
    def setUp(self):
        LOG.info(f'--------{os.path.basename(__file__)} start--------')
        self.constant = Constant()
        self.PrimaryNode = Node('PrimaryDbUser')
        self.sh_primary = CommonSH('PrimaryDbUser')
        self.sh_standby = CommonSH('Standby1DbUser')

    def test_system_internal_tools(self):
        LOG.info('--------step1:关闭主数据库   expect: 成功--------')
        stop_msg = self.sh_primary.stop_db_instance()
        self.assertIn(self.constant.GS_CTL_STOP_SUCCESS_MSG, stop_msg)

        LOG.info('--------step2:备升主failover结合-W参数  expect: 成功--------')
        excute_msg = self.sh_standby.execute_gsctl(
            "failover -W", self.constant.FAILOVER_SUCCESS_MSG, param="-m fast")
        self.assertFalse(excute_msg)
        time.sleep(10)
        LOG.info('--------step3: refreshconf信息写入     expect: 成功--------')
        excute_msg = self.sh_standby.exec_refresh_conf()
        self.assertTrue(excute_msg)

        LOG.info('--------step4:重启集群          expect: 成功--------')
        self.sh_primary.restart_db_cluster()
        status = self.sh_primary.get_db_cluster_status()
        self.assertTrue("Normal" in status or 'Degraded' in status)

        LOG.info('--------step5:检查主备切换      expect: 主备切换成功--------')
        query_msg = self.sh_standby.get_db_cluster_status(param='detail')
        LOG.info(query_msg)
        self.assertIn('S Primary Normal', query_msg)

    def tearDown(self):
        LOG.info('--------step6:环境恢复    expect:成功---------')
        node_msg = self.sh_standby.get_db_cluster_status(param='detail')
        LOG.info(node_msg)
        if 'S Primary Normal' in node_msg:
            LOG.info('---------恢复主备状态---------')
            recover_cmd = f'''source {macro.DB_ENV_PATH};
                        gs_ctl switchover -D {macro.DB_INSTANCE_PATH} -m fast;
                        gs_om -t refreshconf'''
            LOG.info(recover_cmd)
            msg1 = self.PrimaryNode.sh(recover_cmd).result()
            LOG.info(msg1)
        else:
            return '主备节点正常'
        recover_msg = self.sh_standby.get_db_cluster_status(param='detail')
        LOG.info(recover_msg)
        self.assertNotIn('S Primary Normal', recover_msg)
        self.assertIn(self.constant.CLUSTER_NORMAL_MSG, recover_msg)
        LOG.info(f'--------{os.path.basename(__file__)} end--------')
